<template>
  <div class="select-attachment">
    <!--S选择图片的显示区域-->
    <div class="attachments">
      <template v-if="selected_url.length > 0">
        <div
          v-for="(item,index) in selected_url"
          class="item"
          :style="{width: coverSize + 'px',height: coverSize + 'px'}"
        >
          <img :src="item">
          <div
            class="remove"
            @click="remove(index)"
          >
            <img src="./svg/remove.svg">
          </div>
        </div>
      </template>
      <div v-if="selectedAttachment.length < limit" class="item" @click="show_dialog = true"><img class="add" src="./svg/add.svg"></div>
    </div>
    <!--E选择图片的显示区域-->

    <!--S选择图片弹窗-->
    <el-dialog
      title="素材库"
      :visible.sync="show_dialog"
      :destroy-on-close="false"
      append-to-body
      width="950px"
      class="select-attachment-dialog"
      top="5vh"
      @opened="dialogOpened"
    >
      <div slot="title" class="title">
        <el-upload
          ref="upload"
          :action="upload.url"
          :data="upload.data"
          :headers="upload.headers"
          :multiple="true"
          :on-success="uploadSuccess"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </div>
      <div v-infinite-scroll="load" infinite-scroll-disabled="disabled" class="content">
        <image-item
          v-for="(item,index) in list.data"
          :key="item.id"
          :index="index"
          :data="item"
          :limit="limit"
          :number="already_selected_index.length"
          @select="select"
          @unselect="unselect"
          @overstep="overstep"
          @remove="deleteRemove"
        />
        <p v-if="list.loading" class="load-status">加载中...</p>
        <p v-if="list.noMore" class="load-status">没有更多了</p>
      </div>
      <div slot="footer" class="footer">
        <el-button type="primary" @click="confirm">确认</el-button>
      </div>
    </el-dialog>
    <!--E选择图片弹窗-->
  </div>
</template>

<script>
import ImageItem from './components/ImageItem/index'
import { uploadParams } from '../../utils/url'
export default {
  name: 'SelectAttachment',
  components: {
    ImageItem
  },
  model: {
    prop: 'selectedAttachment',
    event: 'confirm'
  },
  props: {
    // 图片封面大小
    coverSize: {
      type: Number,
      default: 100
    },
    // 类型
    type: {
      type: String,
      default: 'image'
    },
    // 可选择数量
    limit: {
      type: Number,
      default: 1
    },
    // 绑定平台id
    carrierId: {
      type: Number,
      default: 0
    },
    selectedAttachment: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      // 组件是否已经打开过
      already_opened: false,
      show_dialog: false,
      list: {
        limit: [0, 24],
        data: [],
        loading: false,
        noMore: false
      },
      // 已经选择图片下标
      already_selected_index: [],
      // 已经选择的图片地址
      selected_url: []
    }
  },
  computed: {
    // 上传组件所需参数
    upload() {
      return {
        data: {
          carrier_id: this.carrierId,
          type: this.type
        },
        ...uploadParams('attachment/upload')
      }
    },
    disabled() {
      return this.list.loading || this.list.noMore
    }
  },
  watch: {
    selectedAttachment(value) {
      if (value.length > 0) {
        this.selectedAttachment.forEach((item, index) => {
          this.$get('attachment/getAttachmentUrl', {
            attachment: item
          })
            .then((res) => {
              this.selected_url.push(res.data.data)
            })
            .catch(() => {
              this.selectedAttachment.splice(index, 1)
            })
        })
      }
    }
  },
  methods: {
    // 下拉加载
    load() {
      this.getList()
    },
    dialogOpened() {
      if (!this.already_opened) {
        this.already_opened = true
      }
    },
    // 点击上传按钮出发文件组件
    uploadSuccess(response, res, files) {
      // S上传成功已经选择的图片下标加上传图片的数量
      const file_number = files.length
      this.already_selected_index.forEach((item, index) => {
        this.already_selected_index[index] = parseInt(this.already_selected_index[index]) + file_number
      })
      // E上传成功已经选择的图片下标加上传图片的数量)
      this.$refs.upload.clearFiles()
      this.list.data.unshift(response.data)
    },
    // 获取素材列表
    getList() {
      if (this.list.loading) return
      this.list.loading = true
      this.$get('attachment/getList', {
        type: this.type,
        limit: this.list.limit,
        carrier_id: this.carrierId
      })
        .then((res) => {
          this.list.loading = false
          // 初始化已经选择的附件
          if (this.selectedAttachment.length > 0) {
            for (let i = this.list.limit[0]; i < this.list.limit[0] + res.data.data.length; i++) {
              const index = i - this.list.limit[0]
              if (this.selectedAttachment.includes(res.data.data[index].attachment)) {
                if (!this.already_selected_index.includes(i)) {
                  this.already_selected_index.push(i)
                  res.data.data[index].selected = 1
                }
              }
            }
          }
          if (res.data.data.length > 0) {
            this.list.limit[0] += this.list.limit[1]
            this.list.data.push(...res.data.data)
          } else {
            this.list.noMore = true
          }
        })
    },
    // 选择图片
    select(index) {
      this.already_selected_index.push(parseInt(index))
      this.$set(this.list.data[index], 'selected', 1)
    },
    // 取消选择图片
    unselect(index) {
      this.already_selected_index.splice(this.already_selected_index.indexOf(parseInt(index)), 1)
      this.$set(this.list.data[index], 'selected', 0)
    },
    // 选中的图片超出数量限制
    overstep() {
      this.$set(this.list.data[this.already_selected_index[0]], 'selected', 0)
      this.already_selected_index.shift()
    },
    // 确认选择
    confirm() {
      const temp_selected_url = []
      const temp_selected_attachment = []
      if (this.already_selected_index.length > 0) {
        this.already_selected_index.forEach((item) => {
          const attachment_data = this.list.data[item]
          // temp_selected_url.push(attachment_data.url)
          temp_selected_attachment.push(attachment_data.attachment)
        })
      }
      this.selected_url = temp_selected_url
      this.$emit('confirm', temp_selected_attachment)
      this.show_dialog = false
    },
    // 删除素材附加
    deleteRemove(index) {
      if (this.already_selected_index.length > 0) {
        this.already_selected_index.forEach((item, _index) => {
          if (item > index) {
            this.already_selected_index[_index] -= 1
          } else if (item === parseInt(index)) {
            this.already_selected_index.splice(_index, 1)
          }
        })
      }
      this.list.data.splice(index, 1)
    },
    // 移除选择的图片
    remove(index) {
      if (this.list.data[this.already_selected_index[index]]) {
        this.$set(this.list.data[this.already_selected_index[index]], 'selected', 0)
      }
      this.already_selected_index.splice(index, 1)
      this.confirm()
    }
  }
}
</script>

<style scoped lang="scss">
.select-attachment{
  background: red;
}
.attachments{
 .item{
   position: relative;
   width: 100px;
   height: 100px;
   background: #eee;
   cursor: pointer;
   float: left;
   margin:0 10px 10px 0;
   .remove{
     position: absolute;
     top:-5px;
     right: -5px;
     width: 20px;
     height: 20px;
     background: #F56C6C;
     border-radius: 10px;
     padding-top: 3px;
     box-sizing: border-box;
     img{
       width: 15px;
       height: 15px;
       display: block;
       margin: 0 auto;
     }
   }
   img{
     width: 100%;
     height: 100%;
     display: block;
     object-fit: contain;
     &.add{
       width: 80%;
       height: 80%;
       margin: 0 auto;
       position: relative;
       top:50%;
       transform: translateY(-50%);
     }
   }
 }
}
.select-attachment-dialog{
  .content{
    height: 350px;
    overflow-y: auto;
    dl{
      width: 100px;
      height: 100px;
      margin: 0;
      dt{
        width: 100%;
        height: 100%;
        background:#eee no-repeat center center;
        background-size: contain;
      }
      dd{
        background: red;
      }
    }
    .load-status{
      width: 100%;
      clear: both;
      text-align: center;
    }
  }
  .footer{
    text-align: center;
  }
}
</style>
